package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelContentService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.ITravelStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import cn.wolfcode.luowowo.cache.vo.TravelStats;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQueryObject;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.query.TravelQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {

    @Value("${file.dir}")
    private String dir;

    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelContentService travelContentService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatsCacheService travelStatsCacheService;

    @RequestMapping("")
    public String index(@ModelAttribute("qo")TravelQueryObject qo , Model model){
        //pageInfo
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "travel/list";
    }

    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        return UploadUtil.upload(pic,dir);
    }

    //UME上传图片 这个富文本编辑器只能接受jsp类型,但是SpringBoot并不支持jsp, 所以直接用java代码写jsp内容返回给文本编辑器
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        java.lang.String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, dir);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @RequiredLogin
    @RequestMapping("/input")
    public String input(Long id, Model model){
        if(id != null){
            //修改, 页面回显
            model.addAttribute("tv",travelService.selectById(id));
        }
        //dests 查询所有目的地
        List<Destination> dests = destinationService.list();
        model.addAttribute("dests",dests);
        return "travel/input";
    }

    @RequestMapping("/getContent")
    @ResponseBody
    public TravelContent getContent(Long id){
        TravelContent content = travelContentService.getTravelContent(id);
        return content;
    }

    @RequiredLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @LoginUser UserInfo userInfo){
        System.out.println(travel);
        //判断当前用户是不是文章的作者
        Long travelId = travel.getId();
        if (travelId != null) {
            Travel t = travelService.selectById(travelId);
            if(!t.getAuthor().getId().equals(userInfo.getId())){
                AjaxResult result = new AjaxResult();
                result.mark("您没有操作权限");
                return result;
            }
        }
        //设置当前游记的作者
        travel.setAuthor(userInfo);
        return travelService.savaOrUpdate(travel);
    }

    @RequestMapping("/detail")
    public String getDetail(Long id , Model model ){
        //detail 根据游记id查询游记内容
        Travel travel = travelService.selectById(id);
        model.addAttribute("detail",travel);

        //toasts
        Long destId = travel.getDest().getId();
        List<Destination> toasts = destinationService.getToasts(destId);
        // 吐司toasts
        model.addAttribute("toasts",toasts);

        //sds 点击量前三的攻略
        List<StrategyDetail> sds = strategyDetailService.listViewnumTop3(destId);
        model.addAttribute("sds",sds);

        //ts 点击量前三的游记
        List<StrategyDetail> ts = travelService.listViewnumTop3(destId);
        model.addAttribute("ts",ts);

        //list 这篇游记的所有评论
        model.addAttribute("list",travelCommentService.listByTravelId(id));

        return "travel/detail";
    }

    @RequestMapping("commentAdd")
    @RequiredLogin
    public String commentAdd(TravelComment comment , @LoginUser UserInfo user,
                             Integer floor, Model model){
        //设置用户数据
        comment.setUserId(user.getId());
        comment.setUsername(user.getNickname());
        comment.setLevel(user.getLevel());
        comment.setHeadUrl(user.getHeadImgUrl());

        //新增评论 , 保存之后会有文档id, 复制给comment
        comment = travelCommentService.save(comment);

        //c 也就是comment
        model.addAttribute("c",comment);

        //floor
        model.addAttribute("floor", ++floor);
        return "travel/commentTpl";
    }

    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long travelId,Model model,@LoginUser UserInfo user){
        AjaxResult result = new AjaxResult();
        if (user == null) {
            result.mark("请先登录");
            result.setCode(102);
            return result;
        }
        boolean flag = travelStatsCacheService.travelIdThumbup(travelId,user.getId());
        result.setSuccess(flag);
        //获取顶的总数
        TravelStats travelStats = travelStatsCacheService.getTravelStats(travelId);
        result.setData(travelStats);
        return result;
    }

}
